package de.szut.tictactoe.gui;

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import de.szut.tictactoe.main.GameController;

public class TicButtonListener extends MouseAdapter {
	private TicButton[][] buttons;
	
	private int[] getPosition(TicButton button) {
		int yindex = 0;
		for (TicButton[] y : buttons) {
			int xindex = 0;
			for (TicButton x : y) {
				if (x == button) {
					int[] result = {xindex, yindex};
					return result;
				}
				xindex ++;
			}
			yindex ++;
		}
		return null;
	}
	
	public TicButtonListener(TicButton[][] buttons) {
		this.buttons = buttons;
	}
	
	public void mouseClicked(MouseEvent arg0) {
		System.out.println("selection");
		int[] position = getPosition((TicButton) arg0.getSource());
		GameController.getInstance().getGame().setValue(position[0],position[1]);
		if (GameController.getInstance().getGame().gameHasEnded()) {
			System.out.println("Done");
			System.exit(0);
		}
		if (GameController.getInstance().getGame().isCurrentPlayer()) {
			((TicButton) arg0.getSource()).setText("X");
		} else {
			((TicButton) arg0.getSource()).setText("O");
		}
		GameController.getInstance().getGame().switchCurrentPlayer();
	}
}
